package org.miyuki4j.cfgtool;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/26/星期六 14:52
 * @Version 1.0
 */
@Slf4j
public class DefaultConfLoader implements ConfLoader {

    public static final DefaultConfLoader INSTANCE = new DefaultConfLoader();

    @Override
    public Pair<Class<? extends Conf>, List<Conf>> loadConfs(TableImportData tableImportData) throws Exception {
        tableImportData.verify();
        Class<? extends Conf> clazz = ConfClassManager.registerConfClass(tableImportData.getFullClassName());
        List<Conf> confs = new ArrayList<>();
        for (TableDataRow row : tableImportData.getRows()) {
            Conf conf = clazz.getDeclaredConstructor().newInstance();
            conf.load(row);
            conf.onLoad();
            confs.add(conf);
        }
        return Pair.of(tableImportData.getConfClazz(), confs);
    }

    @Override
    public Map<Class<? extends Conf>, List<Conf>> loadConfs(List<TableImportData> tableImportDataList) throws Exception {
        Map<Class<? extends Conf>, List<Conf>> confListMap = new LinkedHashMap<>();
        for (TableImportData tableImportData : tableImportDataList) {
            Pair<Class<? extends Conf>, List<Conf>> confListPair = loadConfs(tableImportData);
            confListMap.computeIfAbsent(confListPair.getLeft(), k -> new ArrayList<>()).addAll(confListPair.getRight());
        }
        return confListMap;
    }

}
